package com.kkd.kkdapp.activity;

import java.io.File;
import java.util.ArrayList;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.kkd.kkdapp.R;
import com.kkd.kkdapp.adapter.FileChooserAdapter;
import com.kkd.kkdapp.adapter.FileChooserAdapter.FileInfo;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.utils.FileUtils;

public class FileManagerActivity extends BaseActivity {

	private ListView mGridView;
	private View mBtExit;
	private TextView path_tv;

	private String mSdcardRootPath; // sdcard 根路径
	private String mLastFilePath; // 当前显示的路径
	private String fileName;

	private ArrayList<FileInfo> mFileLists;
	private FileChooserAdapter mAdatper;
	private TextView tv_title_cur;

	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.filechooser_show);
		mSdcardRootPath = getIntent().getStringExtra("rootPath");
		fileName = getIntent().getStringExtra("fileName");
		mBtExit = findViewById(R.id.back);
		mBtExit.setOnClickListener(mClickListener);
		mGridView = (ListView) findViewById(R.id.gvFileChooser);
		mGridView.setDividerHeight(0);
		mGridView.setEmptyView(findViewById(R.id.tvEmptyHint));
		mGridView.setOnItemClickListener(mItemClickListener);
		path_tv = (TextView) findViewById(R.id.path_tv);
		path_tv.setText(mSdcardRootPath + "");
		tv_title_cur = (TextView) findViewById(R.id.tv_title_cur);
		tv_title_cur.setText(fileName);
		setGridViewAdapter(mSdcardRootPath);
		findViewById(R.id.rel_share).setOnClickListener(
				new OnSingleClickListener() {

					@Override
					public void onSingleClick(View v) {
						try {
							File file = new File(FileUtils.getKKDRootPath()
									+ "pdf/" + fileName);
							if (file != null) {
								Intent share = new Intent(Intent.ACTION_SEND);
								share.putExtra(Intent.EXTRA_STREAM,
										Uri.fromFile(file));
								share.setType("*/*");// 此处可发送多种文件
								startActivity(Intent.createChooser(share,
										"Share"));
							}
						} catch (Exception e) {

						}
					}
				});
	}

	// 配置适配器
	private void setGridViewAdapter(String filePath) {
		updateFileItems(filePath);
		mAdatper = new FileChooserAdapter(this, mFileLists);
		mGridView.setAdapter(mAdatper);
	}

	// 根据路径更新数据，并且通知Adatper数据改变
	private void updateFileItems(String filePath) {
		mLastFilePath = filePath;
		if (mFileLists == null)
			mFileLists = new ArrayList<FileInfo>();
		if (!mFileLists.isEmpty())
			mFileLists.clear();

		File[] files = folderScan(filePath);
		if (files == null)
			return;

		for (int i = 0; i < files.length; i++) {
			if (files[i].isHidden() || fileName.equals(files[i].getName())) // 不显示隐藏文件和当前下载的文件
				continue;

			String fileAbsolutePath = files[i].getAbsolutePath();
			String fileName = files[i].getName();
			boolean isDirectory = false;
			if (files[i].isDirectory()) {
				isDirectory = true;
			}
			FileInfo fileInfo = new FileInfo(fileAbsolutePath, fileName,
					isDirectory);
			mFileLists.add(fileInfo);
		}
		// When first enter , the object of mAdatper don't initialized
		if (mAdatper != null)
			mAdatper.notifyDataSetChanged(); // 重新刷新
	}

	// 获得当前路径的所有文件
	private File[] folderScan(String path) {
		File file = new File(path);
		File[] files = file.listFiles();
		return files;
	}

	private View.OnClickListener mClickListener = new OnClickListener() {
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.back:
				setResult(RESULT_CANCELED);
				finish();
				break;

			default:
				break;
			}
		}
	};
	public static final String EXTRA_FILE_CHOOSER = "file_chooser";
	private AdapterView.OnItemClickListener mItemClickListener = new OnItemClickListener() {
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {
			FileInfo fileInfo = (FileInfo) (((FileChooserAdapter) adapterView
					.getAdapter()).getItem(position));
			if (fileInfo.isDirectory()) {// 点击项为文件夹, 显示该文件夹下所有文件
				updateFileItems(fileInfo.getFilePath());
			} else if (fileInfo.isPPTFile()) { // 是ppt文件 ， 则将该路径通知给调用者
				Intent intent = new Intent();
				intent.putExtra(EXTRA_FILE_CHOOSER, fileInfo.getFilePath());
				setResult(RESULT_OK, intent);
				finish();
			} else { // 其他文件.....
				// toast("The format of file is error");
			}
		}
	};

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (event.getAction() == KeyEvent.ACTION_DOWN
				&& event.getKeyCode() == KeyEvent.KEYCODE_BACK) {
			backProcess();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	// 返回上一层目录的操作
	public void backProcess() {
		// 判断当前路径是不是sdcard路径 ， 如果不是，则返回到上一层。
		if (!mLastFilePath.equals(mSdcardRootPath)) {
			File thisFile = new File(mLastFilePath);
			String parentFilePath = thisFile.getParent();
			updateFileItems(parentFilePath);
		} else { // 是sdcard路径 ，直接结束
			setResult(RESULT_CANCELED);
			finish();
		}
	}

	private void toast(CharSequence hint) {
		Toast.makeText(this, hint, Toast.LENGTH_SHORT).show();
	}
}